package com.homework.action;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.json.JSONObject;

import com.homework.service.EditorService;
import com.homework.service.UserService;
import com.opensymphony.xwork2.ActionSupport;


public class EditorAction extends ActionSupport implements ServletRequestAware{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3531122927291260237L;
	HttpServletRequest request = null;
	HttpServletResponse response = null;
	private EditorService editorService;
	private UserService userService;
	private Map<String, String> map = new HashMap<String, String>();
	
	public EditorAction()
	{
		editorService = new EditorService();
		userService = new UserService();
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}


	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}
	
	public String execute() {
		String jsonofTitle = "";
		try {
			jsonofTitle = java.net.URLDecoder.decode(request.getParameter("request"), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String state = request.getParameter("state");
		String homeworkIdT = request.getParameter("homeworkId");
		String character = request.getParameter("character");
		
		if(state.equals("ADD") && character.equals("s")){
			String username = request.getParameter("username");
			int userId = userService.getIdbyName(username);
			
			JSONObject json = new JSONObject();
			if(editorService.saveHomeworkT(jsonofTitle,homeworkIdT,userId)){
				json.put("result", "success");
				map.put("result", "success");
				return "success";
			}
			else{
				json.put("result", "fail");
				map.put("result", "fail");
				return "failed";
			}
		}else{
			JSONObject json = new JSONObject();
			if(editorService.updateHomework(jsonofTitle,homeworkIdT)){
				json.put("result", "success");
				map.put("result", "success");
				return "success";
			}
			else{
				json.put("result", "fail");
				map.put("result", "fail");
				return "fail";
			}
		}		
	}
}
